/*
 * @Copyright: 2023 - 2023 www.hoperun.com Inc. All rights reserved.
 */

package com.lifeservice.common.core.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @author liu_yifeng
 * @function RedisLockUtil
 * @date 2023/2/28 19:41
 */
@Component
@Slf4j
public class RedisLockUtil {
    @Autowired
    public RedisTemplate redisTemplate;

    /**
     * 加锁
     *
     * @param key key
     * @return true 加锁成功 false 加锁失败
     */
    public Boolean getLock(String key) {
        Boolean setResult = redisTemplate.opsForValue().setIfAbsent(key, "lock");
        log.info("get lock key {} result is {}", key, setResult);
        return null == setResult ? false : true;
    }

    /**
     * 释放锁
     *
     * @param key key
     * @return true 释放成功 false 释放失败
     */
    public Boolean releaseLock(String key) {
        Boolean releaseResult = redisTemplate.delete(key);
        log.info("release lock {} result is {}", key, releaseResult);
        return releaseResult;
    }
}
